<?php
// export_csv.php
include("config.php");

// 检查数据库连接
if (!$connect) {
    die("数据库连接失败: " . mysqli_connect_error());
}

// 构建查询条件
$whereClause = [];
if (isset($_GET['keyword']) && !empty($_GET['keyword'])) {
    $keyword = mysqli_real_escape_string($connect, $_GET['keyword']);
    $whereClause[] = "(name LIKE '%$keyword%' OR author LIKE '%$keyword%' OR isbn LIKE '%$keyword%')";
}

if (isset($_GET['category']) && !empty($_GET['category'])) {
    $category = mysqli_real_escape_string($connect, $_GET['category']);
    $whereClause[] = "type = '$category'";
}

if (isset($_GET['status']) && !empty($_GET['status'])) {
    $status = mysqli_real_escape_string($connect, $_GET['status']);
    $whereClause[] = "status = '$status'";
}

// 组合WHERE子句
$where = !empty($whereClause) ? "WHERE " . implode(" AND ", $whereClause) : "";

// 执行查询
$sql = "SELECT * FROM info_book $where ORDER BY id";
$result = mysqli_query($connect, $sql);

if (!$result) {
    die("查询执行失败: " . mysqli_error($connect));
}

// 设置CSV文件头
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=books_export_' . date('Ymd_His') . '.csv');

// 创建输出缓冲区
$output = fopen('php://output', 'w');

// 输出CSV文件的标题行
fputcsv($output, array('ID', '书名', '作者', 'ISBN', '价格', '入库时间', '类别', '入库总量', '状态'));

// 输出数据行
if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        fputcsv($output, array(
            $row['id'],
            $row['name'],
            $row['author'],
            $row['isbn'],
            $row['price'],
            $row['uploadtime'],
            $row['type'],
            $row['total'],
            $row['status']
        ));
    }
}

// 关闭输出缓冲区
fclose($output);

// 释放结果集并关闭连接
mysqli_free_result($result);
mysqli_close($connect);
exit;
?>